package com.rt.tmpt.service.impl;

import com.rt.tmpt.bean.A2Job;
import com.rt.tmpt.dao.intf.IA2JobDao;
import com.rt.tmpt.dao.intf.ITemplateDao;
import com.rt.tmpt.dto.Result;
import com.rt.tmpt.others.quartz2.jobs.BeanObjectJobAction;
import com.rt.tmpt.others.quartz2.jobs.ProcedureJobAction;
import com.rt.tmpt.others.quartz2.manager.AutoJobDTO;
import com.rt.tmpt.others.quartz2.manager.JobManager;
import com.rt.tmpt.service.IQuartzService;
import com.rt.tmpt.utils.DateTool;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

@Service
@Transactional(propagation = Propagation.REQUIRED)
@Slf4j
public class QuartzService implements IQuartzService {


    @Resource
    private IA2JobDao jobDao;
    @Resource
    private JobManager jobManager;
    @Resource
    private IQuartzService quartzService;
    @Resource
    private ITemplateDao templateDao;

    @Override
    public Result timerStartup(long a2Job_id) {
        Result result = new Result();
        //取job
        A2Job job = jobDao.findById(a2Job_id).get();
        jobDao.save(job);//执行时间通过jdbc修改数据库的，缓存要更新下


        int mode = job.getMode();
        String jobName = job.getJobName();
        String jobDes = job.getJobDes();
        String jobClass = job.getJobClass();
        String beanMethod = job.getBeanMethod();
        String expression = job.getExpression();
        String param = job.getParam();

        //加入工作任务
        try {
            AutoJobDTO jobDto = new AutoJobDTO();
            //执行job类
            if (mode == 0) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobManager.addJob(jobDto, Class.forName(jobClass));
            }
            //bean object
            if (mode == 1) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobDto.setBeanObject(job.getJobClass());
                jobDto.setBeanMethod(job.getBeanMethod());
                jobManager.addJob(jobDto, BeanObjectJobAction.class);
            }
            //存储过程
            if (mode == 2) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobDto.setProcedure(job.getJobClass());
                jobManager.addJob(jobDto, ProcedureJobAction.class);
            }

            //startJobs
            jobManager.startJobs();
            System.out.println("------------定时器启动成功：" + job.getJobName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return result.fault("job class 加入失败！ClassNotFoundException" + e.getLocalizedMessage());
        } catch (SchedulerException e) {
            e.printStackTrace();
            return result.fault("job class 加入失败 ！SchedulerException" + e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return result.fault("job class 加入失败 ！Exception" + e.getLocalizedMessage());
        }

        job.setIsActivity(1);
        jobDao.save(job);

        return result.success();
    }


    @Override
    public Result timerStartupImmediately(long a2Job_id) {
        Result result = new Result();

        //shutdown
        result = quartzService.timerShutdown(a2Job_id);

        //DateTool
        //取年月日
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间
        calendar.add(Calendar.SECOND, 5);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String exp = second + " " + minute + " " + hour + " " + day + " " + month + " ? " + year;

        //取job
        A2Job job = jobDao.findById(a2Job_id).get();
        jobDao.save(job);//执行时间通过jdbc修改数据库的，缓存要更新下

        job.setExpression(exp);

        int mode = job.getMode();
        String jobClass = job.getJobClass();


        //加入工作任务
        try {
            AutoJobDTO jobDto = new AutoJobDTO();
            //执行job类
            if (mode == 0) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobManager.addJob(jobDto, Class.forName(jobClass));
            }
            //bean object
            if (mode == 1) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobDto.setBeanObject(job.getJobClass());
                jobDto.setBeanMethod(job.getBeanMethod());
                jobManager.addJob(jobDto, BeanObjectJobAction.class);
            }
            //存储过程
            if (mode == 2) {
                jobDto.setJob_id("" + job.getId());
                jobDto.setJob_name(job.getJobName());
                jobDto.setJob_group(AutoJobDTO._JOB_Group);
                jobDto.setJob_time(job.getExpression());
                jobDto.setProcedure(job.getJobClass());
                jobManager.addJob(jobDto, ProcedureJobAction.class);
            }

            //startJobs
            jobManager.startJobs();
            System.out.println("------------定时器启动成功：" + job.getJobName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return result.fault("job class 加入失败！ClassNotFoundException" + e.getLocalizedMessage());
        } catch (SchedulerException e) {
            e.printStackTrace();
            return result.fault("job class 加入失败 ！SchedulerException" + e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return result.fault("job class 加入失败 ！Exception" + e.getLocalizedMessage());
        }

        job.setIsActivity(1);
        jobDao.save(job);

        return result.success();
    }


    @Override
    public Result timerShutdown(long a2Job_id) {
        Result result = new Result();
        //取job
        A2Job job = jobDao.findById(a2Job_id).get();
        jobDao.save(job);//执行时间通过jdbc修改数据库的，缓存要更新下

        String jobName = job.getJobName();
        String jobDes = job.getJobDes();
        String jobClass = job.getJobClass();
        String expression = job.getExpression();
        String param = job.getParam();

        //Remove Job
        AutoJobDTO jobDto = new AutoJobDTO();
        jobDto.setJob_id("" + job.getId());
        jobDto.setJob_name(job.getJobName());
        jobDto.setJob_group(AutoJobDTO._JOB_Group);
        jobDto.setJob_time(job.getExpression());
        jobManager.removeJob(jobDto);

        job.setIsActivity(0);
        jobDao.save(job);
        System.out.println("------------定时器关闭成功：" + job.getJobName());

        return result.success();
    }


    @Override
    public Result timerRestart(long a2Job_id) {
        Result result = new Result();

        //shutdown
        result = quartzService.timerShutdown(a2Job_id);
        if (!result.isSuccess()) {
            return result;
        }
        //startup
        result = quartzService.timerStartup(a2Job_id);

        return result;
    }


    /**
     * 服务重启时，自动启动所有任务
     */
    @Override
    public Result startAllJob() {
        Result result = new Result();
/*		Search search = new Search();
		search.addFilterEqual("deleteFlag", "0");
		search.addFilterEqual("isActivity", "1");
		List<A2Job> jobList = jobDao.search(search);*/
        A2Job a2Job = new A2Job();
        a2Job.setDeleteFlag(0);
        a2Job.setIsActivity(1);
        List<A2Job> jobList = jobDao.findAll(Example.of(a2Job));


        for (A2Job job : jobList) {
            long jobId = job.getId();
            result = timerStartup(jobId);
            if (!result.isSuccess()) {
                log.info("定时器启动：" + job.getJobName() + "：定时器启动失败");
                System.out.println("定时器启动：" + job.getJobName() + "：定时器启动失败");
                //throw new RuntimeException("定时器启动失败："+result.getContent());
                continue;
            }
            log.info("定时器启动：" + job.getJobName() + "：定时器启动成功");
            System.out.println("定时器启动：" + job.getJobName() + "：定时器启动成功");
        }

        return result.success();
    }


    /**
     * 配置定时执行存储过程
     *
     * @param paramMap
     * @return
     */
    public Result executeProcedureJob(String procedure, Map<String, Object> paramMap) {
        Result result = new Result();

        result = templateDao.executeProcedureJob(procedure, paramMap);

        return result;
    }

    /**
     * spring bean 调用测试
     */
    @Override
    public Result testQuartz(Map<String, Object> paramMap) {
        Result result = new Result();
        System.out.println("----------paramMap size:" + paramMap.keySet().size());

        System.out.println("------------testQuartz:" + DateTool.getCurrentDateStr1("yyyy-MM-dd HH:mm:ss.SSS"));

        return result.success();
    }


}
